package fun.boomcat.luckyhe.mirai.plugin.utils;

import fun.boomcat.luckyhe.mirai.plugin.config.ConfigOperation;
import fun.boomcat.luckyhe.mirai.plugin.mapper.ReplyMapper;
import fun.boomcat.luckyhe.mirai.plugin.mapper.ServeGroupMapper;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Map;

public class MyBatisReplyTableUtil {
    private static SqlSessionFactory sqlSessionFactory;

    //    获取Sql会话
    public static SqlSession getSqlSession() throws IOException {
//        try {
//            if (sqlSessionFactory == null) {
//                InputStream is = Resources.getResourceAsStream("mybatis.xml");
//                sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
//                is.close();
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        if (sqlSessionFactory == null) {
            String driver = "com.mysql.jdbc.Driver";

            Map<String, String> connMap;

            connMap = ConfigOperation.getMySqlConnInfo();

            String url = connMap.get("url");
            String username = connMap.get("username");
            String password = connMap.get("password");

//        MyBatis配置
            DataSource dataSource = getDataSource(driver ,url, username, password);
            TransactionFactory transactionFactory = new JdbcTransactionFactory();
            Environment environment = new Environment("development", transactionFactory, dataSource);
            Configuration configuration = new Configuration(environment);

//        add maps here
            configuration.addMapper(ReplyMapper.class);
            configuration.addMapper(ServeGroupMapper.class);

            sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        }

        return sqlSessionFactory.openSession();
    }

    public static DataSource getDataSource(String driver, String url, String username, String password) {
        PooledDataSource dataSource = new PooledDataSource();

        dataSource.setDriver(driver);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setUrl(url);

        return dataSource;
    }
}